<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="jq/jQuery.js"></script>
    <title>管理员系统</title>
    <!-- 使用内联样式 -->
    <link rel="stylesheet" href="css/admin.css">
    <script src="chartjs/chart.umd.min.js"></script>
    <%
		Object a = session.getAttribute("admin");
		if(a == null){
			response.sendRedirect("adminLogin.jsp");
			return;
		}
	%>
</head>
<body>
    <body>
    <!-- 侧边导航栏 -->
    <div class="sidebar">
        <div class="brand">
            <div class="brand-logo">
                <span>💻</span>
            </div>
            <div class="brand-name">后台管理中心</div>
        </div>
        
        <ul class="nav-menu">
           
            <li class="nav-item active" data-page="comments" id="slelectCmt">
                <div class="nav-icon">💬</div>
                <div class="nav-text">评论管理</div>
            </li>
            <li class="nav-item" data-page="products" id="selectAllGoods">
                <div class="nav-icon">📦</div>
                <div class="nav-text">商品管理</div>
            </li>
            <li class="nav-item" data-page="orders" id="selectAllOrders">
                <div class="nav-icon">📋</div>
                <div class="nav-text">订单管理</div>
            </li>
            <li class="nav-item" data-page="DataOverview" id="alldataOverview">
                <div class="nav-icon">📊</div>
                <div class="nav-text">数据概览</div>
            </li>
            <li class="nav-item" data-page="ManageUser" id="manageUser">
                <div class="nav-icon">👥</div>
                <div class="nav-text">用户管理</div>
            </li>
             <li class="nav-item" data-page="AddNewGoods" id="addNewGoods">
                <div class="nav-icon">🏷️</div>
                <div class="nav-text">添加商品</div>
            </li>
             <li class="nav-item" data-page="ManageSeller" id="manageSeller">
                <div class="nav-icon">🏪</div>
                <div class="nav-text">商家管理</div>
            </li>
        </ul>
        
        <div class="user-panel">
    <div class="user-avatar">管</div>
    <div class="user-info">
        <div class="user-name">${adName}</div>
        <div class="user-role">超级管理员</div>
    </div>
    <button id="logout-btn" class="logout-btn" title="退出登录">
        <span>🚪</span>
    </button>
</div>
    </div>

    <!-- 主内容区 - 多个页面容器 -->
    <div class="main-content">
        
        <!-- 评论管理页面 -->
        <div id="comments" class="page-content active" >
           
        </div> 
        
        <!-- 商品管理页面 -->
        <div class="page-content" id="products">
            
        </div>
        
        <!-- 订单管理页面 -->
        <div id="orders" class="page-content">
            
        </div>
        
        <!-- 数据概览页面 -->
        <div id="DataOverview" class="page-content">
        	<div class="header">
        		<div class="page-title" id="OrderPage">
        			<span>📊</span><span>数据概览</span>
        		</div>
        	</div>
        	<div class="tableBox">
        		<div class="col-md-4 mb-3">
                 	<div class="card">
                     	<div class="card-header">
                         	<h5 class="card-title">商品类别销售占比</h5>
                     	</div>
                     	<div class="card-body">
                         	<div class="chart-container">
                             	<canvas id="categoryChart"></canvas>
                         	</div>
                     	</div>
                 	</div>
            	</div>
        	</div>
        	<div class="tableBox">
        	<div class="cardBody">
                <div class="card-icon">
                     <i class="bi bi-currency-dollar"></i>
                </div>
                <h5 class="card-title">今日销售额</h5>
                <h2 class="card-text" id="todayAmountCard">¥48,562</h2>
            </div>
            <div class="cardBody">
                <div class="card-icon">
                     <i class="bi bi-currency-dollar"></i>
                </div>
                <h5 class="card-title">总销售额</h5>
                <h2 class="card-text" id="allAmountCard">¥48,562</h2>
            </div>
            <div class="cardBody">
                <div class="card-icon">
                     <i class="bi bi-currency-dollar"></i>
                </div>
                <h5 class="card-title" >今日订单数</h5>
                <h2 class="card-text" id="todayOrdersCard">¥48,562</h2>
            </div>
        	<div class="cardBody">
                <div class="card-icon">
                     <i class="bi bi-currency-dollar"></i>
                </div>
                <h5 class="card-title" >总订单数</h5>
                <h2 class="card-text" id="allOrdersCard">¥48,562</h2>
            </div>
        	</div>
        </div> 
        
        <!-- 用户管理页面 -->
        <div class="page-content" id="ManageUser">
        	<div class="header">
        		<div class="page-title" id="OrderPage">
        			<span>👥</span><span>用户管理</span>
        		</div>
        	</div>
        	<div class="searchSpan">
        		<span>
        			请输入用户名：<input type="text" name="userName" id="SelectUserName" class="searchInput" size="200" placeholder="请输入搜索关键字"> 
        			<button id="selectUserName" class="simpleButton">搜索</button>
        		</span>
        	</div>
        	<div class="tableBox">
        		<table class="userTable">
        			<thead>
        				<th>
        					用户名
        				</th>
        				<th>
        					密码
        				</th>
        				<th>
        					昵称
        				</th>
        				<th>
        					电话号码
        				</th>
        				<th>
        					账户状态
        				</th>
        				<th>
        					操作
        				</th>
        			</thead>
        			<tbody id="UsersBox">
        				
        			</tbody>
        		</table>
        		<div id="userPageBar"></div>
        	</div>
        </div>
        
        <!-- 添加商品页面 -->
        <div id="AddNewGoods" class="page-content">
        	<div class="header">
        		<div class="page-title" id="OrderPage">
        			<span>🏷️</span><span>添加商品</span>
        		</div>
        	</div>
        	<div class="searchSpan">
        	<form action="/lego/addGoods.do" method="POST" enctype="multipart/form-data" onsubmit="return checkAddgoodsAll()">
        		<span class="titleInfo">请输入品牌名:</span><input  type="text" name="sellerName" id="onsellerName" class="changeInfoInput" placeholder="最大字符20个"><span id="sellerSpan" class="remainText"></span><br>
				<span class="titleInfo">请输入商品名:</span><input type="text" name="goodsName" class="changeInfoInput" id="ongoodsName" placeholder="最大字符20个"> <span id="checkgoods" class="remainText" ></span><br>
				<span class="titleInfo">请输入商品数量:</span><input pattern="^[1-9]\d*$" type="number" name="quantity" class="changeInfoInput" id="onquantity" placeholder="最大库存5000000个"> <span id="checkquantity" class="remainText"></span><br>
				<span class="titleInfo">请输入商品价格:</span><input type="number" name="price" class="changeInfoInput" id="onprice" placeholder="最高价格5000000"><span id="checkprice" class="remainText"></span> <br>
				<span class="titleInfo">请输入一段关于商品的描述:</span><input type="text" name="description" id="ondescription" class="changeInfoInput" placeholder="最大字符30个"><span class="remainText" id="checkdescription"></span> <br>
				<span class="titleInfo">请输入商品类型:</span><input type="text" name="goodsType" id="ongoodsType" class="changeInfoInput" placeholder="最大字符5个"><span class="remainText" id="checkGoodsType"></span> <br>
				<span class="titleInfo">请提交商品的图片:</span><input type="file" name="goodsImg" accept="image/*" id="ongoodsImg"><span class="remainText" id="checkgoodsImg"></span>
				<!-- img用于预览 用户上传的图片 -->
				<img src=""  id="avatar" display="none"><br>
				<input type="submit" id="addGoods" class="simpleButton" value="添加">
        	</form>
        	</div>
        </div>
        
        <!-- 商家管理页面 -->
        <div id="ManageSeller" class="page-content">
        	<div class="header">
        		<div class="page-title" id="OrderPage">
        			<span>🏪</span><span>商家管理</span>
        		</div>
        	</div>
        	<form action="/lego/addSeller.do" method="POST" enctype="multipart/form-data" onsubmit="return checkSerllerAll()">
        		请输入品牌名:<input  type="text" name="brandName" required><span></span>
				请输入账户名:<input type="text" name="sellerName" required> <span></span>
				请输入账户密码:<input type="text" name="sellerPwd" required> <span></span>
				请提交商家头像:<input type="file" name="sellerImg" accept="image/*" required><span></span>
				<input type="submit" id="addseller" value="添加">
        	</form>
        	<hr>
        	<div class="searchSpan">
        		<span>
        			请输入品牌名：<input type="text" id="SelectSellerName" class="searchInput" size="200" placeholder="请输入搜索关键字"> 
        			<button id="searchSeller" class="simpleButton">搜索</button>
        		</span>
        	</div>
        	
        	<div class="tableBox">
        		<table class="userTable">
        			<thead>
        				<th>
        					品牌名
        				</th>
        				<th>
        					商家账户名
        				</th>
        				<th>
        					商家账户密码
        				</th>
        				<th>
        					操作
        				</th>
        			</thead>
        			<tbody id="sellerBox">
        				
        			</tbody>
        		</table>
        		<div id="sellerPageBar"></div>
        	</div>
        </div>
	</div>
<script>
    var categoryChart;
    function initChart() {
    	var categoryCtx = document.getElementById('categoryChart').getContext('2d');
    	categoryChart = new Chart(categoryCtx, {
        	type: 'doughnut',
        	data: {
            	labels: ['包包','服饰','潮鞋','数码','美妆','手表'], // 初始为空，等待后端数据
            	datasets: [{
               		data: [],
                	backgroundColor: [
                    	'rgba(54, 162, 235, 0.7)',
                    	'rgba(255, 99, 132, 0.7)',
                    	'rgba(255, 206, 86, 0.7)',
                    	'rgba(75, 192, 192, 0.7)',
                    	'rgba(153, 102, 255, 0.7)',
                    	'rgba(159, 156, 173, 0.7)'
                	],
                	borderWidth: 1
            	}]
        	},
        	options: {
            	responsive: true,
            	maintainAspectRatio: false,
            	plugins: {
                	legend: {
                    	position: 'right',
                	}
            	}
        	}
    	});
	}
    $("#alldataOverview").click(function(){
    	$.ajax({
    		url:"/lego/selectOverview.do",
    		type:"Post",
    		success:function(response){
    			$("#todayOrdersCard").text(response[6]);
    			$("#allOrdersCard").text(response[7]);
    			$("#todayAmountCard").text(response[8]);
    			$("#allAmountCard").text(response[9]);
    			console.log(response)
    			if(categoryChart!=undefined){
    				categoryChart.destroy();
    				
    			}
    			initChart();
    			var data = [response[0], response[1], response[2], response[3], response[4],response[5]];
    			categoryChart.data.datasets[0].data = data;
    	        categoryChart.update();
    		}
    	})
    })

    var currentSellerPageNum = 1;
    var currentSellerPageName = "";
    function querySeller(keySname,pageNum){
    	console.log(pageNum)
    	$.ajax({
    		url: '/lego/querySellers.do',
    	    type: 'POST',
    	    data: {
	            brandName:keySname,
	            pageNum:pageNum
	        },
	        success:function(e){
	        	console.log(e);
	        	$("#sellerBox").empty();
	        	for (var i = 0; i < e.users.length; i++) {
					var $tr = $('<tr></tr>');
					var $td1 = $('<td>'+e.users[i].brandName+'</td>');
					var $td2 = $('<td>'+e.users[i].sellerName+'</td>');
					var $td3 = $('<td>'+e.users[i].sellerPwd+'</td>');
					var $td5 = $('<td></td>');
					var $eBtn = $('<button class="btnEdit" onclick="editSeller(this)" id="sellerEdit">编辑</button>');
					var $sBtn = $('<button class="btnEdit" onclick="saveSeller('+e.users[i].sellerId+',this)" style="display:none" id="sellerSave">保存</button>');
					$td5.append($eBtn);
					$td5.append($sBtn);
					$tr.append($td1);
					$tr.append($td2);
					$tr.append($td3);
					$tr.append($td5);
					$("#sellerBox").append($tr);
				}
	        	currentSellerPageNum = e.pageNum;
	        	currentSellerPageName = e.keyUname;
	        	console.log(e.pageNum)
	        	$('#sellerPageBar').empty();
	        	var $shouyea = $('<a onclick=querySeller("'+currentSellerPageName+'",1)>首页</a>');
	        	$('#sellerPageBar').append($shouyea);
	        	
	        	if(e.hasPrev){
	        		var $prev = $('<a onclick=querySeller("'+currentSellerPageName+'",'+(currentSellerPageNum-1)+')>上一页</a>');
	            	$('#sellerPageBar').append($prev);
	        	}
	        	for (var i = 0; i < e.navigatorNums.length; i++) {
	    			if(e.navigatorNums[i]==currentUserPageNum){
	    				var $num = $('<a onclick=querySeller("'+currentSellerPageName+'",'+e.navigatorNums[i]+') class="activeColor">'+e.navigatorNums[i]+'</a>');
	                	$('#sellerPageBar').append($num);
	    			}else{
	    				var $num = $('<a onclick=querySeller("'+currentSellerPageName+'",'+e.navigatorNums[i]+')>'+e.navigatorNums[i]+'</a>');
	                	$('#sellerPageBar').append($num);
	    			}
	    		}
	        	if(e.hasNext){
	        		var $next = $('<a onclick=querySeller("'+currentSellerPageName+'",'+(currentSellerPageNum+1)+')>下一页</a>');
	            	$('#sellerPageBar').append($next);
	        	}
	        	var $shouyea = $('<a onclick=querySeller("'+currentSellerPageName+'",'+e.totalPages+')>尾页</a>');
	        	$('#sellerPageBar').append($shouyea);
	        } 
    	})
    }
    $("#manageSeller").click(function(){
    	querySeller("",1);
    })
    $("#searchSeller").click(function(){
    	var $SelectSellerName = $("#SelectSellerName").val();
    	querySeller($SelectSellerName,1);
	})
    //编辑商家密码
    function editSeller(e){
    	var closestTr = $(e).closest('tr');
    	
		var sellerPwd = closestTr.find('td:eq(2)').text();
		
		// 将单元格内容替换为input框，并设置对应的value值
		closestTr.find('td:eq(2)').html(`<input type="text" class="edit-input" value=`+sellerPwd +`>`);

			// 隐藏编辑按钮，显示保存按钮
		$(e).hide();
		closestTr.find('#sellerSave').show();
    } 
    
    //保存功能
    function saveSeller(id,e){
    	var closestTr = $(e).closest('tr');
    	var pwd = closestTr.find("td:eq(2) input").val().trim(); 

        // 判断密码是否为空
        if (!pwd) {
            alert("密码不能为空");
            return; 
        }
    	$.ajax({
    		url:"/lego/modifySeller.do",
    		type:"POST",
    		data:{
    			sellerId:id,
    			sellerPwd:pwd,
    		},
    		success:function(e){
    			console.log(e)
    			closestTr.find('td:eq(2)').text(pwd);
    			closestTr.find('#sellerSave').hide();
    			closestTr.find('#sellerEdit').show();
    		},
    		error: function(xhr, status, error) {
	            console.log("状态码:", xhr.status);
	            console.log("错误:", error);
	            console.log("原始响应:", xhr.responseText);
	            
	            // 尝试查看原始响应内容
	            try {
	                var rawResponse = xhr.responseText;
	                alert("请求失败，服务器返回: " + rawResponse);
	            } catch(e) {
	                alert("请求失败，且无法读取响应内容");
	            }
	        }
    	})
    };
    
    //失去焦点判断输入的品牌名是否正确
    var isbrand = false;
    $("#onsellerName").blur(function()  {
    	var sellername = $(this).val();
    	$.ajax({
    		url:"/lego/checkSellerName.do",
    		type:"POST",
    		data:{
    			brandName:sellername
    		},
    		success:function(response){
    			if(response=="正确"){
    				$("#sellerSpan").text("正确");
    				isbrand = true;
    			}else{
    				$("#sellerSpan").text("请输入正确的品牌名！");
    				isbrand = false;
    			}
    		}
    	});
	});
    
    //验证是否输入价格的是正数且不为e
    var isprice = false;
    $("#onprice").blur(function(){
    	if ($("#onprice").val()==""||$("#onprice").val()<=0||$("#onquantity").val()>5000000) {
    		$("#onprice").val("");
    		$("#checkprice").text("请输入正确的价格");
    		isprice = false;
        }else{
        	$("#checkprice").text("");
        	isprice = true;
        }
    })
    //验证输入的数量是否为正整数
    var isquantity = false;
    $("#onquantity").blur(function(){
    	if ($("#onquantity").val()==""||$("#onquantity").val()<=0||$("#onquantity").val()>5000000) {
    		$("#onquantity").val("");
    		$("#checkquantity").text("请输入正确的数量");
    		isprice = false;
        }else{
        	$("#checkquantity").text("");
        	isquantity = true;
        }
    });
    //验证输入的描述是否为空
    function isdescription(){
    	var $ondescription = $("#ondescription").val();
    	if($ondescription.length>0&&$ondescription.length<=30){
    		$('#checkdescription').text("");
    		return true;    		
    	}else{
    		$("#ondescription").val("");
    		$('#checkdescription').text("请输入合法的商品描述")
    		return false;
    	}
    }
    //验证商品名是否为空
    function isGoodsName(){
    	var $ongoodsName = $("#ongoodsName").val();
    	if($ongoodsName.length>0&&$ongoodsName.length<=20){
    		$('#checkgoods').text("")
    		return true;    		
    	}else{
    		$("#ongoodsName").val("");
    		$('#checkgoods').text("请输入合法的商品名")
    		return false;
    	}
    }
    //验证类型是否为空
    function isgoodsType(){
    	var $ongoodsType = $("#ongoodsType").val();
    	if($ongoodsType.length>0&&$ongoodsType.length<=5){
    		$('#checkGoodsType').text("")
    		return true;   
    	}else{
    		$("#ongoodsType").val("");
    		$('#checkGoodsType').text("请输入合法的类型")
    		return false;
    	}
    }
    //验证图片是否为空
    function isgoodsImg(){
    	var $ongoodsImg = $("#ongoodsImg").val();
    	if($ongoodsImg.length>0){
    		return true;    		
    	}else{
    		$("#ongoodsImg").val("");
    		$("#checkgoodsImg").text("请上传图片");
    		return false;
    	}
    }
    //表单提交事件
    function checkAddgoodsAll(){
    	if(isbrand&isGoodsName()&isquantity&isprice&isdescription()&isgoodsType()&isgoodsImg()){
    		return true;
    	}
    	return false;
    }
   
    
    //查询所有的用户，动态sql也可输入用户名关键词搜索
    var currentUserPageNum = 1;
    var currentUserPageName = "";
    function queryUser(keyUname,pageNum){
    	$.ajax({
    		url: '/lego/queryUsers.do',
    	    type: 'POST',
    	    data: {
	            userName:keyUname,
	            pageNum:pageNum
	        },
	        success:function(e){
	        	$("#UsersBox").empty();
	        	console.log(e.users)
	        	for (var i = 0; i < e.users.length; i++) {
	        		console.log("1")
					var $tr = $('<tr></tr>');
					var $td1 = $('<td>'+e.users[i].userName+'</td>');
					var $td2 = $('<td>'+e.users[i].password+'</td>');
					var $td3 = $('<td>'+e.users[i].nickName+'</td>');
					var $td4 = $('<td>'+e.users[i].phoneNum+'</td>');
					var $td5 = $('<td></td>');
					if(e.users[i].isDeleted==1){
						var $sBtn = $('<button class="btnSave"  onclick="saveUserInfo('+e.users[i].userId+',this)" style="display:none">保存</button> ');
						var $eBtn = $('<button class="btnEdit" onclick="modifyUserInfo(this)">编辑</button>');
						var $dBtn = $('<button class="btnDelete" onclick="deleteUserInfo('+e.users[i].userId+',this)">删除</button>');
						$td5.append($sBtn);
						$td5.append($eBtn);
						$td5.append($dBtn);
					}else{
						var $dBtn = $('<span>无</span>');
						$td5.append($dBtn);
					}
					$tr.append($td1);
					$tr.append($td2);
					$tr.append($td3);
					$tr.append($td4);
					if(e.users[i].isDeleted==1){
						var $td6 = $('<td>可用账户</td>');
						$tr.append($td6);
					}else{
						var $td6 = $('<td>不可用账户</td>');
						$tr.append($td6);
					}
					$tr.append($td5);
					$("#UsersBox").append($tr);
				}
	        	currentUserPageNum = e.pageNum;
	        	currentUserPageName = e.keyUname;
	        	$('#userPageBar').empty();
	        	var $shouyea = $('<a onclick=queryUser("'+currentUserPageName+'",1)>首页</a>');
	        	$('#userPageBar').append($shouyea);
	        	
	        	if(e.hasPrev){
	        		var $prev = $('<a onclick=queryUser("'+currentUserPageName+'",'+(currentPage-1)+')>上一页</a>');
	            	$('#pageBar').append($prev);
	        	}
	        	for (var i = 0; i < e.navigatorNums.length; i++) {
	    			if(e.navigatorNums[i]==currentUserPageNum){
	    				var $num = $('<a onclick=queryUser("'+currentUserPageName+'",'+e.navigatorNums[i]+') class="activeColor">'+e.navigatorNums[i]+'</a>');
	                	$('#userPageBar').append($num);
	    			}else{
	    				var $num = $('<a onclick=queryUser("'+currentUserPageName+'",'+e.navigatorNums[i]+')>'+e.navigatorNums[i]+'</a>');
	                	$('#userPageBar').append($num);
	    			}
	    		}
	        	if(e.hasNext){
	        		var $next = $('<a onclick=queryUser("'+currentUserPageName+'",'+(currentPage+1)+')>下一页</a>');
	            	$('#userPageBar').append($next);
	        	}
	        	var $shouyea = $('<a onclick=queryUser("'+currentType+'",'+e.totalPages+')>尾页</a>');
	        	$('#userPageBar').append($shouyea);
	        }
    	})
    }
    //删除用户或者修改用户状态
    function deleteUserInfo(id,e){
    	var closestTr = $(e).closest('tr');
    	$.ajax({
    		url: '/lego/deleteUserInfo.do',
    	    type: 'POST',
    	    data: {
	            userId:id
	        },
	        success:function(response){
	        	console.log(e);
	        	console.log(response=="修改");
	        	if(response=="修改"){
	        		$(e).closest('td').empty();
	        	}else{
	        		closestTr.empty();
	        	}
	        }
    	})
    	queryUser(currentUserPageName,currentUserPageNum);
    }
    
    //编辑用户昵称和密码
    function modifyUserInfo(e){
    	var closestTr = $(e).closest('tr');
    	
		var userPwd = closestTr.find('td:nth-child(2)').text();
		var userNick = closestTr.find('td:nth-child(3)').text();
		
		// 将单元格内容替换为input框，并设置对应的value值
		closestTr.find('td:nth-child(2)').html(`<input type="text" class="edit-input" value=`+userPwd+`>`);
		closestTr.find('td:nth-child(3)').html(`<input type="text" class="edit-input" value=`+userNick+`>`);

			// 隐藏编辑按钮，显示保存按钮
		$(e).hide();
		closestTr.find('.btnSave').show();
    } 
    
    //保存功能
    function saveUserInfo(id,e){
    	var closestTr = $(e).closest('tr');
        
    	var pwd=closestTr.find("td:eq(1) input").val().trim();
    	var nick=closestTr.find("td:eq(2) input").val().trim();
    	
    	if (!pwd ) {
            alert("密码不能为空");
            return; 
        }
    	if(!nick){
    		alert("昵称不能为空");
    		return; 
    	}
    	$.ajax({
    		url:"/lego/modify.do",
    		type:"POST",
    		data:{
    			userId:id,
    			userPwd:pwd,
    			userNick:nick
    		},
    		success:function(e){
    			closestTr.find('td:eq(1)').text(pwd);
    			closestTr.find('td:eq(2)').text(nick);
    			
    			closestTr.find('.btnSave').hide();
    			closestTr.find('.btnEdit').show();
    		}
    	})
    };
    
    $('#selectUserName').click(function(){
    	var $keyUnameOfInput = $('#SelectUserName').val();
    	console.log($keyUnameOfInput);
    	queryUser($keyUnameOfInput,1);
    });
    
    
    $('#manageUser').click(function(){
    	queryUser("",1);
    });
    function selectUserReviews(){
    	$.ajax({
    		url:"/lego/selectConment",
    		type:"post",
    		success:function(response){
    			$('#comments').empty();
    			var $CmtHead=$(`<div class="header">
    	                <div class="page-title">
                        <span>💬</span> 用户评论管理
                    </div>`);
    			 var $Cmt_container=$(`<div class="comments-container">
    	                <div class="comments-header">
                        <div class="section-title">最新用户评论</div>
                        <div class="results-count">共 `+response.length+` 条评论</div>
                    </div>`); 
    			 
    			 var $Cmt_ul=$(`<ul class="comments-list" id="comments-ul"></ul>`);
    			$('#comments').append($CmtHead);
    			$('#comments').append($Cmt_container)
    			$('#comments').append($Cmt_ul);
    			
    			for(var i=0;i<response.length;i++){
    				var $Cmt_li=$(`<li class="comment-item"></li>`);
    				
    				$Cmt_li.append(`
    						<div class="comment-header">
                            	<div class="user-info-container">
                                	<div>
                                    	<div class="comment-user">`+ response[i].nickName +`</div>
                                    	<div class="comment-date">`+ response[i].reviewTime+`</div>
                                	</div>
                            	</div>
                        	</div>
                        	<div class="product-info">
                            	<div class="product-details">
                                	<div class="product-name">`+response[i].goodsName+`</div>
                                	<div class="product-category">`+response[i].goodsType+`</div>
                            	</div>
                        	</div>

                        	
                    		<div class="comment-content">`+ response[i].rewContext+`</div>
                    		
                    		<div class="comment-actions">
                            	<button class="action-btn btn-delete">
                            	<span style="display:none" id="reviewId">`+response[i].reviewId+`</span>
                                	<span>🗑️</span> 删除
                            	</button>
                        	</div>`
    				 ); 
    				$('#comments-ul').append($Cmt_li);
    			}
    		}
    		});
    };
    
    selectUserReviews()
    	$(document).on('click',"#slelectCmt",function(){
    		selectUserReviews()
    	});
    	
    $(document).on('click', '.btn-delete', function(){
        var reviewId = $(this).closest('.comment-actions').find('#reviewId').text();
        
        $.ajax({
            url: "/lego/delConmentServlet",
            type: "POST",
            data: { 
                reviewId: reviewId 
            },
            success: function(response) {
                console.log(response);
                if(response.code == 200) {
                    alert("删除成功");
                    selectUserReviews(); // 刷新评论列表
                } 
            },
            error: function(xhr) {
                console.error("错误响应:", xhr.responseText);
                alert("请求失败: " + xhr.responseText);
            }
        });
    });
    
    
        // 页面切换功能
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有导航项的活动状态
                document.querySelectorAll('.nav-item').forEach(navItem => {
                    navItem.classList.remove('active');
                });
                // 添加当前导航项的活动状态
                this.classList.add('active');
                
                // 获取目标页面ID
                const targetPage = this.getAttribute('data-page');
                
                // 隐藏所有页面
                document.querySelectorAll('.page-content').forEach(page => {
                    page.classList.remove('active');
                });
                
                // 显示目标页面
                document.getElementById(targetPage).classList.add('active');
            });
        });
        

        
       
        
        // 显示操作提示
        function showToast(message) {
            const toast = document.createElement('div');
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                bottom: 30px;
                left: 50%;
                transform: translateX(-50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 12px 24px;
                border-radius: 8px;
                z-index: 1000;
                opacity: 0;
                transition: opacity 0.3s;
            `;
            
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.style.opacity = '1';
            }, 10);
            
            setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => {
                    toast.remove();
                }, 300);
            }, 3000);
        }
        
        // 分页按钮事件
        document.querySelectorAll('.pagination button').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelector('.pagination button.active').classList.remove('active');
                this.classList.add('active');
            });
        });
        
        // 统计卡片悬停效果
        document.querySelectorAll('.stat-card').forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-5px)';
                this.style.boxShadow = '0 15px 25px rgba(0, 0, 0, 0.07)';
            });
            
            card.addEventListener('mouseleave', function() {
                this.style.transform = '';
                this.style.boxShadow = '';
            });
        });
        // 退出登录功能
		document.getElementById('logout-btn').addEventListener('click', function() {
   		// 可以在这里添加退出前的确认对话框
    	if(confirm('确定要退出登录吗？')) {
        	// 跳转到登录页面
        	window.location.href = '/lego/admLogout.do';
    	}
		});
//当前页和当前类型        
var currentPage = 1;
var currentType = "";

//添加页码
function addPageBar(response){
	var $pageBar = $('<div id = "pageBar"></div>');
	$('#products').append($pageBar);
	currentPage = response.pageNum;
	currentType = response.goodsType;
	
	var $shouyea = $('<a onclick=changeType("'+currentType+'",1,"")>首页</a>');
	$pageBar.append($shouyea);
	
	if(response.hasPrev){
		var $prev = $('<a onclick=changeType("'+currentType+'",'+(currentPage-1)+',"")>上一页</a>');
    	$('#pageBar').append($prev);
	}
	
	for (var i = 0; i < response.navigatorNums.length; i++) {
		if(response.navigatorNums[i]==currentPage){
			var $num = $('<a onclick=changeType("'+currentType+'",'+response.navigatorNums[i]+',"") class="activeColor">'+response.navigatorNums[i]+'</a>');
        	$('#pageBar').append($num);
		}else{
			var $num = $('<a onclick=changeType("'+currentType+'",'+response.navigatorNums[i]+',"")>'+response.navigatorNums[i]+'</a>');
        	$('#pageBar').append($num);
		}
		
	}
	
	if(response.hasNext){
		var $next = $('<a onclick=changeType("'+currentType+'",'+(currentPage+1)+',"")>下一页</a>');
    	$('#pageBar').append($next);
	}
	var $shouyea = $('<a onclick=changeType("'+currentType+'",'+response.totalPages+',"")>尾页</a>');
	$('#pageBar').append($shouyea)
}	
        //发起ajax请求
        function changeType(type,pageNum,keyWord){
        	var pageSize = 10;
        	$.ajax({
        	    url: '/lego/selectGoods.do',
        	    type: 'POST',
        	    data: {
    	            goodsType:type,
    	            keyWord:keyWord,
    	            pageNum:pageNum,
    	            pageSize:pageSize
    	        },
        	    success: function(response) {
        	    	$('#products').empty();
        	    	console.log(response)
                    addPageBar(response); 
        	    	var $pageTitle = $('<div class="page-title" id="GoodsPage"></div>');
                    var $span = $('<span>📦</span><span>商品管理</span>');
                    var $goodsDiv = $(`<div id="goodsDiv">
                    
                            	搜索商品:<input type="text" id="selectGds" name="selectGds">
                    <button id="slctGdsBtn">搜索</button>
                    
                </div>`);
                    var $table = $(`<table id="goodsTable">
                    <tr>
                    	<td>名字</td>
                    	<td>数量</td>
                    	<td>价格</td>
                    	<td>类型</td>
                    	<td>操作</td>
                    </tr>
                    </table>`);
                    $('#products').append($pageTitle);
        			$('#GoodsPage').append($span);
                    $('#products').append($goodsDiv);
                    $('#products').append($table);
                    for (var i = 0; i < response.data.length; i++) {
                    	var item = response.data[i];
                    	var $tr = $('<tr></tr>')
                    	var $goodsId =$('<td style="display:none">'+response.data[i].goodsId+'</td>')
                    	var $goodsName = $('<td class="goods-name">'+response.data[i].goodsName+'</td>');
                    	var $goodsNum = $('<td class="goods-quantity">'+response.data[i].quantity+'</td>');
                    	var $goodsPrice = $('<td class="goods-price">'+response.data[i].price+'</td>');
                    	var $goodsType = $('<td class="goods-type">'+response.data[i].goodsType+'</td>');
                    	
                    	$('#goodsTable').append($tr);
                    	$tr.append($goodsId);
                    	$tr.append($goodsName);
                    	$tr.append($goodsNum);
                    	$tr.append($goodsPrice);
                    	$tr.append($goodsType);
                    	$tr.append(`<td class="actions">
                                <button class="butn-delete">下架</button>
                                <button class="butn-edit">修改</button>
                                <button class="butn-save" style="display:none">保存</button>
                            </td>`);
                    	
					}
                    $('#slctGdsBtn').click(function() {
                        var searchKeyword = $('#selectGds').val(); // 获取输入框的值
                        var selectedType = $('#goodsType').val(); // 获取下拉框选中的值
                        changeType(selectedType, 1, searchKeyword); // 传递搜索关键词
                    });                

        	    },
        	   error: function(xhr, status, error) {
        	        console.error("AJAX请求失败:");
        	        console.log("状态码:", xhr.status);
        	        console.log("错误:", error);
        	        console.log("响应:", xhr.responseText);
        	        if(xhr.status === 404) {
        	            alert("接口不存在，请检查URL路径");
        	        }
        	    }
        	});
        }
        
        $(document).on('click', '.butn-delete', function(){
            // 获取当前行的商品ID
            var goodsId = $(this).closest('tr').find('td:first').text(); // 获取第一个td的内容
            console.log("要下架的商品ID:", goodsId);
            
            // 发送AJAX请求
            $.ajax({
                url: "/lego/updateGoodsQuantity.do",
                type: "POST",
                data: { 
                    goodsId: goodsId 
                },
                success: function(response) {
                    if(response.code == 200) {
                        alert("下架成功");
                        // 可选：移除该行或刷新列表
                        changeType(currentType, currentPage, "");
                    } else {
                        alert("下架失败: " + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("AJAX请求失败:", xhr.responseText);
                    alert("请求失败: " + xhr.responseText);
                }
            });
        });
        
        //修改按钮
        $(document).on('click', '.butn-edit', function(){
    		var $tr = $(this).closest('tr');
    		var goodsId = $tr.find('td:first').text();  
    		var goodsName = $tr.find('td:nth-child(2)').text();
    		var goodsNum = $tr.find('td:nth-child(3)').text();
    		var goodsPrice = $tr.find('td:nth-child(4)').text();
    		var goodsType = $tr.find('td:nth-child(5)').text();
    			// 将单元格内容替换为input框，并设置对应的value值
   			 $tr.find('td:nth-child(2)').html(`<input type="text" class="edit-input" value=`+goodsName+`>`);
    		 $tr.find('td:nth-child(3)').html(`<input type="number" class="edit-input" value=`+goodsNum+`>`);
   			 $tr.find('td:nth-child(4)').html(`<input type="number" step="0.01" class="edit-input" value=`+goodsPrice+`>`);
  			 $tr.find('td:nth-child(5)').html(`<input type="text" class="edit-input" value=`+goodsType+`>`);
    
    			// 隐藏编辑按钮，显示保存按钮
    		$(this).hide();
    		$tr.find('.butn-save').show();
		})
		//保存
		$(document).on('click', '.butn-save', function(){
    		var $tr = $(this).closest('tr');
    		
    		var goodsId = $tr.find('td:first').text();
    		var goodsName = $tr.find('td:eq(1) input').val();
    		var goodsNum = parseInt($tr.find('td:eq(2) input').val());
    		var goodsPrice = parseFloat($tr.find('td:eq(3) input').val());
    		var goodsType = $tr.find('td:eq(4) input').val();
    
   			$.ajax({
        		url: '/lego/updateGoods.do',
        		type: "post",
        		data: {
           			goodsId: goodsId,
            		goodsName: goodsName,
            		goodsNum: goodsNum,  // 保持与后端一致
            		goodsPrice: goodsPrice,  // 保持与后端一致
            		goodsType: goodsType
        		},
        		success: function(response){
            		// 更新成功后恢复显示
            		$tr.find('td:eq(1)').text(goodsName);
            		$tr.find('td:eq(2)').text(goodsNum);
            		$tr.find('td:eq(3)').text(goodsPrice);
            		$tr.find('td:eq(4)').text(goodsType);
            
            		$tr.find('.butn-save').hide();
            		$tr.find('.butn-edit').show();
        		},
        		error: function(xhr, status, error) {
            		console.error("保存失败:", error);
            		alert("保存失败，请重试");
        		}	
    		});
		});

        
	$("#selectAllGoods").click(function(e) {
		changeType("推荐",1,"");
	});
	
	function addOrdersPage(response) {
	    var $pageBar = $('<div id="pageBar"></div>');
	    $('#orders').empty().append($pageBar);
	    
	    currentPage = response.pageNum;
	    currentOrderStatus = response.orderStatus || "";

	    // 首页按钮
	    $pageBar.append($('<a class="page-link" data-page="1">首页</a>'));

	    // 上一页按钮
	    if (response.hasPrev) {
	        $pageBar.append($('<a class="page-link" data-page="' + (currentPage - 1) + '">上一页</a>'));
	    }

	    // 页码按钮
	    for (var i = 0; i < response.navigatorNums.length; i++) {
	        var pageNum = response.navigatorNums[i];
	        var $num = $('<a class="page-link" data-page="' + pageNum + '">' + pageNum + '</a>');
	        if (pageNum == currentPage) {
	            $num.addClass('activeColor');
	        }
	        $pageBar.append($num);
	    }

	    // 下一页按钮
	    if (response.hasNext) {
	        $pageBar.append($('<a class="page-link" data-page="' + (currentPage + 1) + '">下一页</a>'));
	    }

	    // 尾页按钮
	    $pageBar.append($('<a class="page-link" data-page="' + response.totalPages + '">尾页</a>'));
	}

	// 事件委托：绑定分页按钮点击（在页面加载完成后执行）
	$(document).on('click', '#pageBar a.page-link', function() {
	    var pageNum = $(this).data('page');
	    selectOrder(currentOrderStatus, pageNum, 0);
	});
	function selectOrder(orderStatus,pageNum,userId){
    	var pageSize = 8;
    	$.ajax({
    	    url: '/lego/selectUserOrders.do',
    	    type: 'POST',
    	    data: {
                orderStatus: orderStatus,
                userId: userId,  // 添加缺失的userId参数
                pageNum: pageNum,
                pageSize: pageSize
            },
    	    success: function(response) {
    	    	$('#orders').empty();
    	    	console.log(response);
    	    	addOrdersPage(response);
                var $header = $('<div class="header"></div>');
    	    	var $pageTitle = $('<div class="page-title" id="OrderPage"></div>');
                var $span = $('<span>📦</span><span>订单管理</span>');
                var $input = $('<span class="searchSpan">请输入订单id:<input type="text" class="searchInput"><button class="searchBtn">搜索</button></span>')
                var $table = $(`<table id="ordersTable">
                        <tr>
                        	<td>订单号</td>
                        	<td>商品名字</td>
                        	<td>用户名字</td>
                        	<td>地址</td>
                        	<td>金额</td>
                        	<td>下单时间</td>
                        	<td>到达时间</td>
                        	<td>状态</td>
                        	<td>操作</td>
                        </tr>
                        </table>`);
				$('#orders').append($header);
				$header.append($pageTitle);
				$pageTitle.append($span);
				$('#orders').append($input);
				$('#orders').append($table);
				
				for (var i = 0; i < response.orders.length; i++) {
					var $tr = $('<tr></tr>');
					var $ordersId = $('<td style="display:none">'+response.orders[i].orderId+'</td>');
                	var $ordersNum = $('<td>'+response.orders[i].orderNumber+'</td>');
                	var $userId = $('<td style="display:none">'+response.orders[i].userId+'</td>');
                	var $goodsId = $('<td style="display:none">'+response.orders[i].goodsId+'</td>');
                	var $goodsName = $('<td>'+response.orders[i].goodsName+'</td>');
                	var $userName = $('<td>'+response.orders[i].userName+'</td>');
                	var $totalAmount = $('<td>¥'+(response.orders[i].totalAmount ? response.orders[i].totalAmount.toFixed(2) : '0.00')+'</td>');
                	if(response.orders[i].receivingAddress == null){
                		var $receivingAddress = $('<td>无</td>');
                    	var $orderTime = $('<td>'+response.orders[i].orderTime+'</td>');
                    	if(response.orders[i].orderStatus == "pending"){
                    		var $deliveryTime = $('<td>未送达</td>');
                    		var $orderStatus = $('<td>待付款</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                    	if(response.orders[i].orderStatus == "processing"){
                    		var $deliveryTime = $('<td>未送达</td>');
                    		var $orderStatus = $('<td>待发货</td>');
                    		var $doBtn = $('<td><button class="smBtn">发货</button></td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                            $tr.append($doBtn);
                    	}
                    	if(response.orders[i].orderStatus == "shipped"){
                    		var $deliveryTime = $('<td>未送达</td>');
                    		var $orderStatus = $('<td>待送达</td>');
                    		var $doBtn = $('<td><button class="deBtn">送达</button></td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                            $tr.append($doBtn);
                    	}
                    	if(response.orders[i].orderStatus == "delivered"){
                    		var $deliveryTime = $('<td>'+response.orders[i].deliveryTime+'</td>');
                    		var $orderStatus = $('<td>已送达</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                    	if(response.orders[i].orderStatus == "toBeReviewed"){
                    		var $deliveryTime = $('<td>'+response.orders[i].deliveryTime+'</td>');
                    		var $orderStatus = $('<td>已送达</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                    	if(response.orders[i].orderStatus == "finished"){
                    		var $deliveryTime = $('<td>'+response.orders[i].deliveryTime+'</td>');
                    		var $orderStatus = $('<td>已送达</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                	}else{
                		var $receivingAddress = $('<td>'+response.orders[i].receivingAddress+'</td>');
                    	var $orderTime = $('<td>'+response.orders[i].orderTime+'</td>');
                    	if(response.orders[i].orderStatus == "pending"){
                    		var $deliveryTime = $('<td>未送达</td>');
                    		var $orderStatus = $('<td>待付款</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                    	if(response.orders[i].orderStatus == "processing"){
                    		var $deliveryTime = $('<td>未送达</td>');
                    		var $orderStatus = $('<td>待发货</td>');
                    		var $doBtn = $('<td><button class="smBtn">发货</button></td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                            $tr.append($doBtn);
                    	}
                    	if(response.orders[i].orderStatus == "shipped"){
                    		var $deliveryTime = $('<td>未送达</td>');
                    		var $orderStatus = $('<td>待送达</td>');
                    		var $doBtn = $('<td><button class="deBtn">送达</button></td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                            $tr.append($doBtn);
                    	}
                    	if(response.orders[i].orderStatus == "delivered"){
                    		var $deliveryTime = $('<td>'+response.orders[i].deliveryTime+'</td>');
                    		var $orderStatus = $('<td>已送达</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                    	if(response.orders[i].orderStatus == "toBeReviewed"){
                    		var $deliveryTime = $('<td>'+response.orders[i].deliveryTime+'</td>');
                    		var $orderStatus = $('<td>已送达</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                    	if(response.orders[i].orderStatus == "finished"){
                    		var $deliveryTime = $('<td>'+response.orders[i].deliveryTime+'</td>');
                    		var $orderStatus = $('<td>已送达</td>');
                            $table.append($tr);
                            $tr.append($ordersId);
                            $tr.append($ordersNum);
                            $tr.append($userId);
                            $tr.append($goodsId);
                            $tr.append($goodsName);
                            $tr.append($userName);
                            $tr.append($receivingAddress);
                            $tr.append($totalAmount);
                            $tr.append($orderTime);
                            $tr.append($deliveryTime);
                            $tr.append($orderStatus);
                    	}
                	}
                	
				}
    	    },
    	   error: function(xhr, status, error) {
    	        console.error("AJAX请求失败:");
    	        console.log("状态码:", xhr.status);
    	        console.log("错误:", error);
    	        console.log("响应:", xhr.responseText);
    	        if(xhr.status === 404) {
    	            alert("接口不存在，请检查URL路径");
    	        }
    	    }
    	});
    }
	$(document).on('click', '.smBtn', function(){
	    var st = "shipped";
	    var oId = $(this).closest('tr').find('td:first').text();
	    
	    $.ajax({
	        url: '/lego/changeStaById.do',
	        type: 'POST',
	        dataType: 'json',
	        data: {
	            orderStatus: st,
	            orderId: oId,
	        },
	        success: function(result) {
	            if(result && result.code == 200) {
	                alert("发货状态更新成功");
	                selectOrder(currentOrderStatus, currentPage, 0);
	            } else {
	                alert("操作失败: " + (result ? result.message : "未知错误"));
	            }
	        },
	        error: function(xhr, status, error) {
	            console.error("AJAX请求失败:");
	            console.log("状态码:", xhr.status);
	            console.log("错误:", error);
	            console.log("原始响应:", xhr.responseText);
	            
	            // 尝试查看原始响应内容
	            try {
	                var rawResponse = xhr.responseText;
	                alert("请求失败，服务器返回: " + rawResponse);
	            } catch(e) {
	                alert("请求失败，且无法读取响应内容");
	            }
	        }
	    });
	});
	$(document).on('click', '.deBtn', function(){
	    var st = "delivered";
	    var oId = $(this).closest('tr').find('td:first').text();
	    
	    $.ajax({
	        url: '/lego/changeStaById.do',
	        type: 'POST',
	        dataType: 'json',
	        data: {
	            orderStatus: st,  // 确保包含这个参数
	            orderId: oId,
	        },
	        success: function(result) {
	            if(result && result.code == 200) {
	                alert("订单状态已更新为已送达");
	                selectOrder(currentOrderStatus, currentPage, 0); // 刷新列表
	            } else {
	                alert("操作失败: " + (result ? result.message : "未知错误"));
	            }
	        },
	        error: function(xhr, status, error) {
	            console.error("AJAX请求失败:");
	            console.log("状态码:", xhr.status);
	            console.log("错误:", error);
	            console.log("原始响应:", xhr.responseText);
	            
	            try {
	                var rawResponse = xhr.responseText;
	                alert("请求失败，服务器返回: " + rawResponse);
	            } catch(e) {
	                alert("请求失败，且无法读取响应内容");
	            }
	        }
	    });
	});
	$("#selectAllOrders").click(function(e) {
		selectOrder("",1,0);
	});
	$(document).on('click', '.allBtn', function(e) {
	    selectOrder("", 1, 0);
	});
	$(document).on('click', '.searchBtn', function(){
		
		var oNum = $(".searchInput").val();
		$.ajax({
	        url: '/lego/selectOrderByONum.do',
	        type: 'POST',
	        dataType: 'json',
	        data: {
	            orderNum: oNum,
	        },
	        success: function(response) {
	        	$('#orders').empty();
	        	var $header = $('<div class="header"></div>');
    	    	var $pageTitle = $('<div class="page-title" id="OrderPage"></div>');
                var $span = $('<span>📦</span><span>订单管理</span>');
                var $input = $('<span class="searchSpan">请输入订单id:<input type="text" class="searchInput"><button class="searchBtn">搜索</button><button class="allBtn">显示全部</button></span>')
                var $table = $(`<table id="ordersTable">
                        <tr>
                        	<td>订单号</td>
                        	<td>商品名字</td>
                        	<td>用户名字</td>
                        	<td>地址</td>
                        	<td>金额</td>
                        	<td>下单时间</td>
                        	<td>到达时间</td>
                        	<td>状态</td>
                        	<td>操作</td>
                        </tr>
                        </table>`);
				$('#orders').append($header);
				$header.append($pageTitle);
				$pageTitle.append($span);
				$('#orders').append($input);
				$('#orders').append($table);
				var $tr = $('<tr></tr>');
				var $ordersId = $('<td style="display:none">'+response.orderId+'</td>');
            	var $ordersNum = $('<td>'+response.orderNumber+'</td>');
            	var $userId = $('<td style="display:none">'+response.userId+'</td>');
            	var $goodsId = $('<td style="display:none">'+response.goodsId+'</td>');
            	var $goodsName = $('<td>'+response.goodsName+'</td>');
            	var $userName = $('<td>'+response.userName+'</td>');
            	var $totalAmount = $('<td>¥'+(response.totalAmount ? response.totalAmount.toFixed(2) : '0.00')+'</td>');
            	/* var $totalAmount = $('<td>¥'+(response.orders[i].totalAmount ? response.orders[i].totalAmount.toFixed(2) : '0.00')+'</td>'); */
            	if(response.receivingAddress == null){
            		var $receivingAddress = $('<td>无</td>');
                	var $orderTime = $('<td>'+response.orederTime+'</td>');
                	if(response.orderStatus == "pending"){
                		var $deliveryTime = $('<td>未送达</td>');
                		var $orderStatus = $('<td>待付款</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
                	if(response.orderStatus == "processing"){
                		var $deliveryTime = $('<td>未送达</td>');
                		var $orderStatus = $('<td>待发货</td>');
                		var $doBtn = $('<td><button class="smBtn">发货</button></td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                        $tr.append($doBtn);
                	}
                	if(response.orderStatus == "shipped"){
                		var $deliveryTime = $('<td>未送达</td>');
                		var $orderStatus = $('<td>待送达</td>');
                		var $doBtn = $('<td><button class="deBtn">送达</button></td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                        $tr.append($doBtn);
                	}
                	if(response.orderStatus == "delivered"){
                		var $deliveryTime = $('<td>'+response.deliveryTime+'</td>');
                		var $orderStatus = $('<td>已送达</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
                	if(response.orderStatus == "toBeReviewed"){
                		var $deliveryTime = $('<td>'+response.deliveryTime+'</td>');
                		var $orderStatus = $('<td>已送达</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
                	if(response.orderStatus == "finished"){
                		var $deliveryTime = $('<td>'+response.deliveryTime+'</td>');
                		var $orderStatus = $('<td>已送达</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
            	}else{
            		var $receivingAddress = $('<td>'+response.receivingAddress+'</td>');
                	var $orderTime = $('<td>'+response.orderTime+'</td>');
                	if(response.orderStatus == "pending"){
                		var $deliveryTime = $('<td>未送达</td>');
                		var $orderStatus = $('<td>待发货</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
                	if(response.orderStatus == "processing"){
                		var $deliveryTime = $('<td>未送达</td>');
                		var $orderStatus = $('<td>待发货</td>');
                		var $doBtn = $('<td><button class="smBtn">发货</button></td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                        $tr.append($doBtn);
                	}
                	if(response.orderStatus == "shipped"){
                		var $deliveryTime = $('<td>未送达</td>');
                		var $orderStatus = $('<td>待送达</td>');
                		var $doBtn = $('<td><button class="deBtn">送达</button></td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                        $tr.append($doBtn);
                	}
                	if(response.orderStatus == "delivered"){
                		var $deliveryTime = $('<td>'+response.deliveryTime+'</td>');
                		var $orderStatus = $('<td>已送达</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
                	if(response.orderStatus == "toBeReviewed"){
                		var $deliveryTime = $('<td>'+response.deliveryTime+'</td>');
                		var $orderStatus = $('<td>已送达</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
                	if(response.orderStatus == "finished"){
                		var $deliveryTime = $('<td>'+response.deliveryTime+'</td>');
                		var $orderStatus = $('<td>已送达</td>');
                        $table.append($tr);
                        $tr.append($ordersId);
                        $tr.append($ordersNum);
                        $tr.append($userId);
                        $tr.append($goodsId);
                        $tr.append($goodsName);
                        $tr.append($userName);
                        $tr.append($receivingAddress);
                        $tr.append($totalAmount);
                        $tr.append($orderTime);
                        $tr.append($deliveryTime);
                        $tr.append($orderStatus);
                	}
            	}
	        },
	        error: function(xhr, status, error) {
	            console.log("状态码:", xhr.status);
	            console.log("错误:", error);
	            console.log("原始响应:", xhr.responseText);
	            
	            // 尝试查看原始响应内容
	            try {
	                var rawResponse = xhr.responseText;
	                alert("请求失败，服务器返回: " + rawResponse);
	            } catch(e) {
	                alert("请求失败，且无法读取响应内容");
	            }
	        }
	    });
	});


	document.getElementById("ongoodsImg").addEventListener("change",function(event){
		let file = event.target.files[0];
		console.log(file);
		if(file){
			let reader = new FileReader();
			reader.onload = function(e){
				document.getElementById("avatar").src=e.target.result;
				document.getElementById("avatar").style.display="inline";
			}
			reader.readAsDataURL(file);
		}
	});

    </script>
</body>
</html>